#include "anip.h"
#include "color/truecolor.h"
#include "ui/controls.h"
#include "ui/helpers.h"
#include "ui/colorpicker.h"

using namespace anip;

class MainWindow : public ui::Window
{
private:
	ui::ColorPickerBase* cp = nullptr;
	ui::RadioBar* provider, * intention;
	ui::Label* label = nullptr;

public:
	MainWindow(): Window(nullptr)
	{
		markTopLevel();
		Font f = FontManager::get({ "std-latin", "std-chn" }, 18);
		setFont(f);
		setInheritFont(f);
		setText(L"取色器");

		wstring ps[]{ L"HSV", L"LAB", L"hLC", L"hLS"};
		provider = ui::FlowHelper::radioBar(*this, 4, ps);
		provider->items[1].select();
		ui::FlowHelper::endRow(*this);

		const TrivariateColorProvider* prs[]{ 
			TrivariateColorProvider::HSV,
			TrivariateColorProvider::CIELAB,
			TrivariateColorProvider::CIEhLC,
			TrivariateColorProvider::CIEhLS};
		for (int i = 0; i < 4; i++)
		{
			auto pp = prs[i];
			provider->items[i].onClick = [&, pp](ui::RadioBarItem& self)
			{
				makeColorPicker(pp);
			};
		}

		label = ui::FlowHelper::label(*this, L"");
		ui::FlowHelper::endRow(*this);

		makeColorPicker(TrivariateColorProvider::CIELAB);
	}

	void makeColorPicker(const TrivariateColorProvider* p)
	{
		TrueColor tc{ 50, 0, 0 };
		bool isNew = false;
		if (cp != nullptr)
		{
			tc = cp->getColor();
			cp->markDelete();
			isNew = true;
		}
		cp = new ui::RectangularColorPicker(
			(ui::Container*)nullptr, { 0, 0 }, { 400, 600 }, p, tc);
		insertChild(*cp, *label);
		cp->layoutOptions.type = LayoutOptions::Flow;
		cp->layoutOptions.stretchX = 1;
		cp->onColorChanged = [&](ui::ColorPickerBase& self)
		{
			TrueColor c = self.getColor();
			color srgb;
			TrueColor::to_sRGB(&c, &srgb);

			wstring text = L"RGB:\n";
			text +=
				L">      (" + toString(srgb.r)
				+ L", " + toString(srgb.g)
				+ L", " + toString(srgb.b) + L")\n>      or ";
			text +=
				L"(" + toString((int)(srgb.r * 255))
				+ L", " + toString((int)(srgb.g * 255))
				+ L", " + toString((int)(srgb.b * 255)) + L")\nCIELAB (D50):\n";
			text +=
				L">      (" + toString(c.L)
				+ L", " + toString(c.a)
				+ L", " + toString(c.b) + L")";
			label->setText(text);
		};
		
	}

	void processParentResize() override
	{
		cp->setSize(_size);
	}

	using Window::mainLoop;
};

int main(int argc, char** argv)
{
	std::cout << "Loading... \n";
	anip::init();
	Context::init({ 600, 900 });
	Context::maxFramerate = 48;
	TrueColor::init();

	FontManager::addFace("std-latin", "fonts/arial.ttf");
	FontManager::addFace("std-chn", "fonts/simhei.ttf");
	FontManager::init();
	std::cout << "done." << std::endl;

	ui::Control::setUIScaling(1.5);
	auto w = new MainWindow();
	w->mainLoop();
	delete w;

	FontManager::finalize();
	anip::finalize();
	return 0;
}